<?php
class Users_Admin extends MX_Controller
{
    private $_last_message = '';
    function __construct()
    {
        parent::__construct();
        if(!modules::run('auth/auth/has_permission', array('operation' => OPERATION_MANAGE))) redirect('/');
    }

    /**
     * Sắp xếp layout, chuẩn bị dữ liệu cho module users
     *
     * @param type $method
     * @param type $para1
     * @param type $para2
     */
    function dispatcher($method='dashboard', $para1=NULL, $para2=NULL)
    {
        $layout             = 'powercms/admin_layout';
        $current_url        = '';

        switch ($method)
        {
            case 'list_user':
                $main_content           = $this->list_users(array('page' => $para1));
                $current_url            = '/dashboard/users';
                break;
            case 'add_user':
                $main_content           = $this->add_user();
                break;
            case 'edit_user':
                $main_content           = $this->edit_user(array('user_id' => $para1));
                break;
            case 'delete_user':
                $main_content           = $this->delete_user(array('user_id' => $para1));
                break;
        }

        $view_data                  = array();
        $view_data['url']           = isset($current_url) ? $current_url : '';
        $view_data['admin_menu']    = modules::run('menus/menus/get_dashboard_menus');
        $view_data['main_content']  = $main_content;
        // META data
        $view_data['title']         = $this->_title;
        $this->load->view($layout, $view_data);
    }

    function list_users($options = array())
    {
        $options                = array_merge($options, $this->_prepare_search($options));
        $options['is_admin']    = TRUE;
        $total_row              = $this->users_model->get_users_count($options);
        $total_pages            = (int)($total_row / USERS_PER_PAGE);
        if ($total_pages * USERS_PER_PAGE < $total_row) $total_pages++;
        if ((int)$options['page'] > $total_pages) $options['page'] = $total_pages;

        $options['offset']  = $options['page'] <= DEFAULT_PAGE ? DEFAULT_OFFSET : ((int)$options['page'] - 1) * USERS_PER_PAGE;
        $options['limit']   = USERS_PER_PAGE;
//        $options['role_id'] = ID_MANAGER;
        $config = prepare_pagination(
            array(
                'total_rows'    => $total_row,
                'per_page'      => $options['limit'],
                'offset'        => $options['offset'],
                'js_function'   => 'change_page_admin'
            )
        );
        $this->pagination->initialize($config);

        $view_data  = array();
        //$countries
        $view_data['page_links']    = $this->pagination->create_ajax_links();
        $view_data['users']         = $this->users_model->get_users($options);
        $view_data['total_rows']    = $total_row;
        $view_data['total_pages']   = $total_pages;
        $view_data['page']          = $options['page'];
        $view_data['filter']        = $options['filter'];
        //heading
        $this->_title       = 'Quản lý người dùng' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/users_list', $view_data, TRUE);
    }


    /*
     * Thêm mới user
     */
    function add_user()
    {
        $options    = array();
        if($this->is_postback())
        {
            if (!$this->_do_add_user())
                $options['error'] = validation_errors();
        }
        $view_data = $this->_get_add_user_form_data();
        
        if (isset($options['error'])) $view_data['options']   = $options;

        $this->_title               = 'Thêm quản trị viên' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_user_form', $view_data, TRUE);
    }
 /**
     * Chuẩn bị dữ liệu cho form add
     * @return type
     */
    private function _get_add_user_form_data()
    {
        $view_data                  = array();
        $view_data['username']      = $this->input->post('username');
        $view_data['password']      = $this->input->post('password');
        $view_data['fullname']      = $this->input->post('fullname');
        $view_data['phone']         = $this->input->post('phone');
        $view_data['address']       = $this->input->post('address');
        $view_data['email']         = $this->input->post('email');
        $view_data['role_combo']    = $this->users_model->get_roles_combo(array('roles' => $this->input->post('roles')));
        $view_data['header']        = 'Thêm quản trị viên';
        $view_data['button_name']   = 'Thêm';
        $view_data['submit_uri']    = '/dashboard/users/add';
        return $view_data;
    }
     private function _do_add_user()
    {
        $this->form_validation->set_rules('username', 'Tên Đăng Nhập', 'trim|required|min_length[5]|xss_clean');
        $this->form_validation->set_rules('password', 'Mật khẩu', 'trim|required|min_length[5]|xss_clean');
        $this->form_validation->set_rules('fullname', 'Họ và Tên', 'trim|required|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean|');
        $this->form_validation->set_rules('phone', 'Số điện thoại', 'trim|required|xss_clean|is_numberic');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'trim|required|xss_clean');
        $this->form_validation->set_rules('roles', 'Quyền', 'trim|is_not_default_combo');
        
        if ($this->form_validation->run())
        {
            $post_data = $this->_get_posted_user_data();

            $users = $this->users_model->get_users(array('username'=> $post_data['username'],'last_row' => TRUE));
            if(is_object($users))
                return FALSE;
            $this->users_model->add_user($post_data);

            redirect('/dashboard/users/' . $this->phpsession->get('current_support_lang'));
        }
        return FALSE;
    }

    private function _get_posted_user_data(){
        $view_data                          = array();
        $view_data['username']       = $this->input->post('username');
        $view_data['password']       = md5($this->input->post('password'));
        $view_data['fullname']       = $this->input->post('fullname');
        $view_data['phone1']         = $this->input->post('phone');
        $view_data['address']        = $this->input->post('address');
        $view_data['email']          = $this->input->post('email');
        $view_data['roles_id']       = $this->input->post('roles');
        $view_data['joined_date']    = date('Y-m-d H:i:s');
        return $view_data;
    }


    /**
     * Thực hiện việc sửa nội dung sản phẩm.
     *
     */
    function edit_user($options = array())
    {
        // Nếu là postback thì lưu dữ liệu và quay trở lại trang danh sách
        if ($this->is_postback())
        {
            if (!$this->_do_edit_user($options))
                $options['error'] = $this->_last_message;
        }
        // Hiển thị form sửa sản phẩm
        $view_data                  = $this->_get_edit_user_form_data($options);
        if (isset($options['error'])) $view_data['options'] = $options;
        $view_data['submit_uri']   = '/dashboard/users/edit/'.$options['user_id'];
        $view_data['header']        = 'Sửa Thông tin quản trị viên';
        $view_data['button_name']   = 'Sửa Thông tin quản trị viên';
        $view_data['is_edit']       = TRUE;
        //heading
        $this->_title               = 'Sửa Thông tin quản trị viên' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_user_form', $view_data, TRUE);
    }

    /**
     * Lấy dữ liệu cho form đăng sản phẩm mới
     */
    private function _get_edit_user_form_data($options = array())
    {
        $user_id                     = $options['user_id'];
        $view_data                   = array();

        // Get from DB
        if(!$this->is_postback())
        {
            $users                       = $this->users_model->get_users(array('id' => $user_id, 'is_admin' => TRUE, 'last_row'=> 'ok'));
            if(!is_object($users)) show_404();
            $view_data['username']      = $users->username;
            $view_data['id']            = $users->id;
            $view_data['password']      = '';
            $view_data['email']         = $users->email;
            $view_data['fullname']      = $users->fullname;
            $view_data['address']       = $users->address;
            $view_data['phone']         = $users->phone1;
            $view_data['role_combo']    = $this->users_model->get_roles_combo(array('roles' => $users->roles_id));
        }
//        // Get from submit
        else
        {
            $view_data                  = array();
            $view_data['username']      = $this->input->post('username');
            $view_data['password']      = $this->input->post('password');
            $view_data['fullname']      = $this->input->post('fullname');
            $view_data['phone']         = $this->input->post('phone');
            $view_data['address']       = $this->input->post('address');
            $view_data['email']         = $this->input->post('email');
            $view_data['role_combo']    = $this->users_model->get_roles_combo(array('roles' => $this->input->post('roles')));
        }
        return $view_data;
    }

    /**
     * Thực hiện việc thêm sản phẩm vào trong DB
     * @return type
     */
    private function _do_edit_user($options = array())
    {
        $this->form_validation->set_rules('username', 'Tên Đăng Nhập', 'trim|required|min_length[5]|xss_clean');
        $this->form_validation->set_rules('fullname', 'Họ và Tên', 'trim|required|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean|');
        $this->form_validation->set_rules('phone', 'Số điện thoại', 'trim|required|xss_clean|is_numberic');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'trim|required|xss_clean');
        $this->form_validation->set_rules('roles', 'Quyền', 'trim|is_not_default_combo');

        if ($this->form_validation->run($this))
        {

            $view_data                          = array();
            if($this->input->post('password') != '')
                $view_data['password']   = md5($this->input->post('password'));
            $view_data['fullname']       = $this->input->post('fullname');
            $view_data['phone1']         = $this->input->post('phone');
            $view_data['address']        = $this->input->post('address');
            $view_data['email']          = $this->input->post('email');
            $view_data['roles_id']       = $this->input->post('roles');
            $view_data['id']            = $options['user_id'];
            $this->users_model->update_user($view_data);
            redirect('/dashboard/users');
        }
        $this->_last_message = validation_errors();
        return FALSE;
    }

    function delete_user($options = array())
    {
        $user_id = $options['user_id'];
        
        $arr = $this->users_model->get_users(array('id' => $user_id, 'last_row'=>'last_row'));
        
        if(!is_object($arr)){
             show_404('');
        }
        // xóa ảnh
        $this->users_model->delete_user($user_id);
        redirect('/dashboard/users');
    }


    function process_status()
    {
        $id = $this->input->post('id');
        $user = $this->users_model->get_users(array('id' =>$id, 'is_admin' => TRUE));
        $status = $user->status == ACTIVE_PRODUCT ? INACTIVE_PRODUCT : ACTIVE_PRODUCT;
        $this->users_model->change_status($id, $status);
    }


    private function _prepare_search($options = array())
    {
        $view_data = array();
        // nếu submit
        if($this->is_postback())
        {
            $this->phpsession->save('user_search', $this->db->escape_str($this->input->post('search')));

            $view_data['search'] = $this->phpsession->get('user_search');
        }
        else
        {
            $view_data['search'] = $this->phpsession->get('user_search');

        }
        $options['keyword']                 = $this->phpsession->get('user_search');
        $options['filter']                  = $this->load->view('admin/filter_form', $view_data, TRUE);
        return $options;
    }
}
?>
